#include "SocketObj/Socketobj.h"
#include <cstring>

SocketObj::SocketObj(const std::string &ip, int port)
{
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        throw std::runtime_error("Socket creation failed");
    }

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr(ip.c_str());

    // 连接到服务器
    if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        throw std::runtime_error("Connection to server failed");
    }
}

SocketObj::~SocketObj()
{
    if (sockfd != -1)
    {
        close(sockfd);
    }
}

ssize_t SocketObj::sendData(const void *buffer, size_t len)
{
    ssize_t sent_bytes = send(sockfd, buffer, len, 0);
    if (sent_bytes == -1)
    {
        throw std::runtime_error("Send failed");
    }
    return sent_bytes;
}

ssize_t SocketObj::recvData(void *buffer, size_t len)
{
    ssize_t recv_bytes = recv(sockfd, buffer, len, 0);
    if (recv_bytes == -1)
    {
        throw std::runtime_error("Receive failed");
    }
    return recv_bytes;
}
